package com.le.tester.imooc.oldimmortal.coding.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.LinkedList;

/**
 * createTime：2025-05-20 17:35
 * description：实例的映射
 */
public class ObjectFactory {
    public static <T> T newInstance(Class<T> cls) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

        //这里类的映射是可以拿到注解的
        Annotation[] annotation = cls.getAnnotations();
        LinkedList<IAspect> iAspects = new LinkedList<>();

//        这里主要是拿到想要的注解
        for (Annotation anItem : annotation) {
            if (anItem instanceof Aspect) {
                Class type = ((Aspect) anItem).type();
                IAspect iAspect = (IAspect) (type.getConstructor().newInstance());
                iAspects.push(iAspect);
            }
        }

        T instance = cls.getConstructor().newInstance();


        return (T) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), (proxy, method, args) -> {
            iAspects.forEach(IAspect::before);
            Object invoke = method.invoke(instance);
            iAspects.forEach(IAspect::after);
            return invoke;
        });
    }
}
